package com.ruoyi.web.controller.wxpay;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.domain.server.Mem;
import com.ruoyi.system.domain.Invite;
import com.ruoyi.system.domain.Member;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.InviteService;
import com.ruoyi.system.service.MemberService;
import com.ruoyi.web.config.WxPayConfig;
import com.ruoyi.web.mapper.OrderInfoMapper;
import com.ruoyi.web.pojo.OrderInfo;
import com.ruoyi.web.pojo.TransferResult;
import com.ruoyi.web.pojo.WechatPayNotification;
import com.ruoyi.web.pojo.WechatPayNotifyBody;
import com.ruoyi.web.uniEnum.OrderInfoEnum;
import com.ruoyi.web.util.AesUtil;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.app.model.Transaction;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/*
 *  @author 雨安
 *  类名： UniPay
 *  创建时间：2025/2/19
 */
@RestController
@RequestMapping("/uni/pay")
public class UniPayController {

    //支付配置
    @Resource
    private WxPayConfig wxPayConfig;

    //订单表
    @Resource
    private OrderInfoMapper orderInfoMapper;

    //用户
    @Resource
    private SysUserMapper sysUserMapper;

    //会员表
    @Resource
    private MemberService memberService;

    //关联表
    @Resource
    private InviteService inviteService;


    //商户打款回调
    @PostMapping("/withdrawal/success")
    public void withdrawal(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("打款通知来了========================================水水水水水水水水水水水水111111111111111111");
        try {
            // 读取请求体的信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            // 逐行读取请求体
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            // 获取完整的 JSON 字符串
            String jsonData = stringBuilder.toString();
            System.out.println("Received JSON data: " + jsonData);
            // 解析 JSON 数据 (可以使用 JSON 库，例如 Jackson 或 Gson)
            // 这里使用 Jackson 作为示例
            ObjectMapper objectMapper = new ObjectMapper();
            TransferNotification notification = objectMapper.readValue(jsonData, TransferNotification.class);

            byte[] apiV3Key  = wxPayConfig.getApiV3Key().getBytes(StandardCharsets.UTF_8);
            byte[] associatedData = notification.getResource().getAssociated_data().getBytes(StandardCharsets.UTF_8);
            // 示例随机数（nonce）
            byte[] nonce = notification.getResource().getNonce().getBytes(StandardCharsets.UTF_8); // 替换为你的随机数，通常是 12 字节
            //密文
            String ciphertext = notification.getResource().getCiphertext();
            //创建实例
            AesUtil aesUtil = new AesUtil(apiV3Key);
            //调用解密方法
            String decryptedText = aesUtil.decryptToString(associatedData, nonce, ciphertext);
            //识别并转换成指定对象
            TransferResult result = objectMapper.readValue(decryptedText, TransferResult.class);
            //判断是否状态为成功
            if (result.getState().equals("SUCCESS")){
                orderInfoMapper.update(null,new UpdateWrapper<OrderInfo>().lambda()
                        //订单号
                        .eq(OrderInfo::getOrderNo,result.getOutBillNo())
                        //设置修改人
                        .set(OrderInfo::getUpdateBy,"微信转账成功")
                        //设置修改时间
                        .set(OrderInfo::getUpdateTime,new Date())
                        //设置打款状态
                        .set(OrderInfo::getOrderType,OrderInfoEnum.TiXianWanCheng.getType())
                );
            }
            // 响应微信服务器
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write("<xml><return_code>SUCCESS</return_code></xml>");
        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 定义一个类来映射 JSON 数据
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class TransferNotification {
        private String id;
        private String create_time ;
        private String event_type;
        private String resource_type;
        private Resource resource;
        private String summary;
        @Data
        @AllArgsConstructor
        @NoArgsConstructor
        public static class Resource {
            private String algorithm;
            private String ciphertext;
            private String associated_data;
            private String original_type;
            private String nonce;
        }
    }

    @PostMapping("/pay/success")
    public void payMemberSuccess(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("我是测试查看是否进入回调========================================");
        try {
            //读取请求体的信息
            ServletInputStream inputStream = request.getInputStream();
            //String拼接对象
            StringBuffer stringBuffer = new StringBuffer();
            //创建buffer对象
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            //定义读取对象
            String s;
            //读取回调请求体
            while ((s = bufferedReader.readLine()) != null) {
                stringBuffer.append(s);
            }
            //定义s1
            String s1 = stringBuffer.toString();
            // 获取时间戳
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            // 获取随机字符串
            String nonce = request.getHeader("Wechatpay-Nonce");
            // 获取签名类型
            String signType = request.getHeader("Wechatpay-Signature-Type");
            // 获取商户证书序列号
            String serialNo = request.getHeader("Wechatpay-Serial");
            // 获取签名
            String signature = request.getHeader("Wechatpay-Signature");
            // 如果已经初始化了 RSAAutoCertificateConfig，可直接使用 没有的话，则构造一个
            NotificationConfig config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(wxPayConfig.getMchId())
                    .privateKeyFromPath(wxPayConfig.getPrivateKeyPath())
                    .merchantSerialNumber(wxPayConfig.getMchSerialNo())
                    .apiV3Key(wxPayConfig.getApiV3Key())
                    .build();
            // 初始化 NotificationParser
            NotificationParser parser = new NotificationParser(config);
            //获取内容
            RequestParam requestParam=new RequestParam.Builder().serialNumber(serialNo).nonce(nonce).signature(signature).timestamp(timestamp)
                    // 若未设置signType，默认值为 WECHATPAY2-SHA256-RSA2048
                    .signType(signType).body(s1).build();
            //创建转换对象
            ObjectMapper objectMapper = new ObjectMapper();
            //得到转换对象
            WechatPayNotification notification = objectMapper.readValue(requestParam.getBody(), WechatPayNotification.class);
            //得到byte
            byte[] apiV3Key  = wxPayConfig.getApiV3Key().getBytes(StandardCharsets.UTF_8);
            //得到byte
            byte[] associatedData = notification.getResource().getAssociatedData().getBytes(StandardCharsets.UTF_8);
            // 示例随机数（nonce）
            byte[] nonce2 = notification.getResource().getNonce().getBytes(StandardCharsets.UTF_8); // 替换为你的随机数，通常是 12 字节
            //密文
            String ciphertext = notification.getResource().getCiphertext();
            //创建实例
            AesUtil aesUtil = new AesUtil(apiV3Key);
            //调用解密方法
            String decryptedText = aesUtil.decryptToString(associatedData, nonce2, ciphertext);
            //结果
            System.out.println(decryptedText + "我是结果对象查看=======================");
            //得到结果
            WechatPayNotifyBody wechatPayNotifyBody = objectMapper.readValue(decryptedText, WechatPayNotifyBody.class);
            //判断支付
            if (Objects.nonNull(wechatPayNotifyBody.getTradeStateDesc()) && wechatPayNotifyBody.getTradeStateDesc().equals("支付成功")){
                //查询订单
                OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                        //订单号
                        .eq(OrderInfo::getOrderNo, wechatPayNotifyBody.getOutTradeNo())
                        //逻辑删除
                        .eq(OrderInfo::getDeleteFlag, Boolean.FALSE)
                );
                //判断订单对象不为 null
                if (Objects.nonNull(orderInfo) && Objects.nonNull(orderInfo.getMemberId())){
                    //查询开通会员对象
                    Member member = memberService.getById(orderInfo.getMemberId());
                    //查询登录用户
                    SysUser sysUser = sysUserMapper.selectUserById(orderInfo.getUserId());
                    //创建新的日期对象
                    LocalDate newDate;
                    //设置会员有效期
                    if (Objects.isNull(sysUser.getMemberEndTime())){
                        //获取添加时间
                        newDate = LocalDate.now().plusDays(member.getDay());
                        //得到转换后的时间
                        String format = newDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        //设置会员有效期
                        sysUser.setMemberEndTime(java.sql.Date.valueOf(format));
                    }else if (Objects.nonNull(sysUser.getMemberEndTime()) && sysUser.getMemberEndTime().after(new Date())){
                        //获取今天日期
                        java.util.Date memberEndTime = sysUser.getMemberEndTime();
                        //获取时间
                        LocalDate memberEndLocalDate = memberEndTime.toInstant()
                                .atZone(ZoneId.systemDefault())
                                .toLocalDate();
                        //累加
                        newDate = memberEndLocalDate.plusDays(member.getDay());
                        //得到转换后的时间
                        String format = newDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        //设置日期
                        sysUser.setMemberEndTime(java.sql.Date.valueOf(format));
                    }else{
                        //获取添加时间
                        newDate = LocalDate.now().plusDays(member.getDay());
                        //得到转换后的时间
                        String format = newDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        //设置会员有效期
                        sysUser.setMemberEndTime(java.sql.Date.valueOf(format));
                    }
                    //执行修改数据库
                    orderInfoMapper.update(null,new UpdateWrapper<OrderInfo>().lambda()
                            //订单号
                            .eq(OrderInfo::getOrderNo,wechatPayNotifyBody.getOutTradeNo())
                            //逻辑删除
                            .eq(OrderInfo::getDeleteFlag,Boolean.FALSE)
                            //设置状态
                            .set(OrderInfo::getOrderType, OrderInfoEnum.FukuanChengGong.getType())
                    );
                    //设置会员编号
                    sysUser.setMemberId(orderInfo.getMemberId());
                    //执行修改
                    sysUserMapper.updateUser(sysUser);
                    //判断是否有上下级
                    List<Invite> list = inviteService.list(new LambdaQueryWrapper<Invite>()
                            //邀请人编号
                            .eq(Invite::getInviteUserId, orderInfo.getUserId())
                    );
                    //遍历邀请集合
                    for (Invite invite : list) {
                        if (Objects.nonNull(invite)){
                            //判断是否为 直推
                            if (invite.getInviteType() == 1){
                                //查询直推用户
                                SysUser ztUser = sysUserMapper.selectUserById(invite.getUserId());
                                //判断直推用户不为 null
                                if (Objects.nonNull(ztUser)){
                                    //查询用户是为高级会员
                                    if (Objects.nonNull(ztUser.getMemberId()) && ztUser.getMemberEndTime().after(new Date())){
                                        System.out.println("进入了直推会员");
                                        //获取本次瓜分的金额
                                        BigDecimal canObtain = member.getPrice().multiply(BigDecimal.valueOf(0.30));
                                        //添加可获取的收益
                                        BigDecimal userFund = ztUser.getIncome().add(canObtain);
                                        //设置用户收益
                                        ztUser.setIncome(userFund);
                                        //设置默认值
                                        ztUser.setUpdateTime(new Date());
                                        ztUser.setUpdateBy("用户邀请收益获取");
                                        //添加用户收益订单
                                        OrderInfo obtainOrderInfo = new OrderInfo();
                                        //设置订单号
                                        obtainOrderInfo.setOrderNo("邀请用户开通会员收益,无订单号");
                                        //设置金额
                                        obtainOrderInfo.setFund(member.getPrice().multiply(BigDecimal.valueOf(0.30)));
                                        //设置用户编号
                                        obtainOrderInfo.setUserId(ztUser.getUserId());
                                        //设置订单备注
                                        obtainOrderInfo.setDescription("邀请用户会员开通");
                                        //设置订单状态
                                        obtainOrderInfo.setOrderType(OrderInfoEnum.PingTaiYaoQingShouYi.getType());
                                        //设置默认值
                                        obtainOrderInfo.setCreateTime(new Date());
                                        obtainOrderInfo.setCreateBy("平台邀请收益(高级会员)");
                                        obtainOrderInfo.setUpdateTime(new Date());
                                        obtainOrderInfo.setUpdateBy("平台邀请收益(高级会员)");
                                        obtainOrderInfo.setDeleteFlag(Boolean.FALSE);
                                        //执行添加
                                        orderInfoMapper.insert(obtainOrderInfo);
                                        //设置团队收益
                                        ztUser.setTeamBenefits(ztUser.getTeamBenefits().add(member.getPrice().multiply(BigDecimal.valueOf(0.30))));
                                        //执行修改
                                        sysUserMapper.updateUser(ztUser);
                                    }else{
                                        System.out.println("进入了直推非会员");
                                        //进入此处代表不是高级会员
                                        //获取本次瓜分的金额
                                        BigDecimal canObtain = member.getPrice().multiply(BigDecimal.valueOf(0.10));
                                        //添加可获取的收益
                                        BigDecimal userFund = ztUser.getIncome().add(canObtain);
                                        //设置用户收益
                                        ztUser.setIncome(userFund);
                                        //设置默认值
                                        ztUser.setUpdateTime(new Date());
                                        ztUser.setUpdateBy("用户邀请收益获取");
                                        //添加用户收益订单
                                        OrderInfo obtainOrderInfo = new OrderInfo();
                                        //设置订单号
                                        obtainOrderInfo.setOrderNo("邀请用户开通会员收益,无订单号");
                                        //设置金额
                                        obtainOrderInfo.setFund(member.getPrice().multiply(BigDecimal.valueOf(0.10)));
                                        //设置用户编号
                                        obtainOrderInfo.setUserId(ztUser.getUserId());
                                        //设置订单备注
                                        obtainOrderInfo.setDescription("邀请用户会员开通");
                                        //设置订单状态
                                        obtainOrderInfo.setOrderType(OrderInfoEnum.PingTaiYaoQingShouYi.getType());
                                        //设置默认值
                                        obtainOrderInfo.setCreateTime(new Date());
                                        obtainOrderInfo.setCreateBy("平台邀请收益(初级会员)");
                                        obtainOrderInfo.setUpdateTime(new Date());
                                        obtainOrderInfo.setUpdateBy("平台邀请收益(初级会员)");
                                        obtainOrderInfo.setDeleteFlag(Boolean.FALSE);
                                        //执行添加
                                        orderInfoMapper.insert(obtainOrderInfo);
                                        //设置团队收益
                                        ztUser.setTeamBenefits(ztUser.getTeamBenefits().add(member.getPrice().multiply(BigDecimal.valueOf(0.10 ))));
                                        //执行修改
                                        sysUserMapper.updateUser(ztUser);
                                    }
                                }
                            }
                            //判断是否为 间推
                            if (invite.getInviteType() == 2){
                                //查询间推用户
                                SysUser jtUser = sysUserMapper.selectUserById(invite.getUserId());
                                //判断直推用户不为 null
                                if (Objects.nonNull(jtUser)){
                                    //查询用户是为高级会员
                                    if (Objects.nonNull(jtUser.getMemberId()) && jtUser.getMemberEndTime().after(new Date())){
                                        System.out.println("进入了简推会员");
                                        //获取本次瓜分的金额
                                        BigDecimal canObtain = member.getPrice().multiply(BigDecimal.valueOf(0.15));
                                        //添加可获取的收益
                                        BigDecimal userFund = jtUser.getIncome().add(canObtain);
                                        //设置用户收益
                                        jtUser.setIncome(userFund);
                                        //设置默认值
                                        jtUser.setUpdateTime(new Date());
                                        jtUser.setUpdateBy("用户邀请收益获取");
                                        //添加用户收益订单
                                        OrderInfo obtainOrderInfo = new OrderInfo();
                                        //设置订单号
                                        obtainOrderInfo.setOrderNo("邀请用户开通会员收益,无订单号");
                                        //设置金额
                                        obtainOrderInfo.setFund(member.getPrice().multiply(BigDecimal.valueOf(0.15)));
                                        //设置用户编号
                                        obtainOrderInfo.setUserId(jtUser.getUserId());
                                        //设置订单备注
                                        obtainOrderInfo.setDescription("邀请用户会员开通");
                                        //设置订单状态
                                        obtainOrderInfo.setOrderType(OrderInfoEnum.PingTaiYaoQingShouYi.getType());
                                        //设置默认值
                                        obtainOrderInfo.setCreateTime(new Date());
                                        obtainOrderInfo.setCreateBy("平台邀请收益(高级会员)");
                                        obtainOrderInfo.setUpdateTime(new Date());
                                        obtainOrderInfo.setUpdateBy("平台邀请收益(高级会员)");
                                        obtainOrderInfo.setDeleteFlag(Boolean.FALSE);
                                        //执行添加
                                        orderInfoMapper.insert(obtainOrderInfo);
                                        //设置团队收益
                                        jtUser.setTeamBenefits(jtUser.getTeamBenefits().add(member.getPrice().multiply(BigDecimal.valueOf(0.15 ))));
                                        //执行修改
                                        sysUserMapper.updateUser(jtUser);
                                    }else{
                                        System.out.println("进入了简推非会员" + member.getPrice().multiply(BigDecimal.valueOf(0.05)));
                                        //进入此处代表不是高级会员
                                        //获取本次瓜分的金额
                                        BigDecimal canObtain = member.getPrice().multiply(BigDecimal.valueOf(0.05));
                                        //添加可获取的收益
                                        BigDecimal userFund = jtUser.getIncome().add(canObtain);
                                        //设置用户收益
                                        jtUser.setIncome(userFund);
                                        //设置默认值
                                        jtUser.setUpdateTime(new Date());
                                        jtUser.setUpdateBy("用户邀请收益获取");
                                        //添加用户收益订单
                                        OrderInfo obtainOrderInfo = new OrderInfo();
                                        //设置订单号
                                        obtainOrderInfo.setOrderNo("邀请用户开通会员收益,无订单号");
                                        //设置金额
                                        obtainOrderInfo.setFund(member.getPrice().multiply(BigDecimal.valueOf(0.05)));
                                        //设置用户编号
                                        obtainOrderInfo.setUserId(jtUser.getUserId());
                                        //设置订单备注
                                        obtainOrderInfo.setDescription("邀请用户会员开通");
                                        //设置订单状态
                                        obtainOrderInfo.setOrderType(OrderInfoEnum.PingTaiYaoQingShouYi.getType());
                                        //设置默认值
                                        obtainOrderInfo.setCreateTime(new Date());
                                        obtainOrderInfo.setCreateBy("平台邀请收益(初级会员)");
                                        obtainOrderInfo.setUpdateTime(new Date());
                                        obtainOrderInfo.setUpdateBy("平台邀请收益(初级会员)");
                                        obtainOrderInfo.setDeleteFlag(Boolean.FALSE);
                                        //执行添加
                                        orderInfoMapper.insert(obtainOrderInfo);
                                        //设置团队收益
                                        jtUser.setTeamBenefits(jtUser.getTeamBenefits().add(member.getPrice().multiply(BigDecimal.valueOf(0.05))));
                                        //执行修改
                                        sysUserMapper.updateUser(jtUser);
                                    }
                                }//判断间推用户不为 null
                            }
                        }//判断遍历对象不为 null

                    }//for each结束


                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    //支付回调通知
    @PostMapping("/success")
    public void pay(HttpServletRequest request, HttpServletResponse response) {
        try {
            //读取请求体的信息
            ServletInputStream inputStream = request.getInputStream();
            //String拼接对象
            StringBuffer stringBuffer = new StringBuffer();
            //创建buffer对象
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            //定义读取对象
            String s;
            //读取回调请求体
            while ((s = bufferedReader.readLine()) != null) {
                stringBuffer.append(s);
            }
            //定义s1
            String s1 = stringBuffer.toString();
            // 获取时间戳
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            // 获取随机字符串
            String nonce = request.getHeader("Wechatpay-Nonce");
            // 获取签名类型
            String signType = request.getHeader("Wechatpay-Signature-Type");
            // 获取商户证书序列号
            String serialNo = request.getHeader("Wechatpay-Serial");
            // 获取签名
            String signature = request.getHeader("Wechatpay-Signature");
            // 如果已经初始化了 RSAAutoCertificateConfig，可直接使用 没有的话，则构造一个
            NotificationConfig config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(wxPayConfig.getMchId())
                    .privateKeyFromPath(wxPayConfig.getPrivateKeyPath())
                    .merchantSerialNumber(wxPayConfig.getMchSerialNo())
                    .apiV3Key(wxPayConfig.getApiV3Key())
                    .build();

            System.out.println(config + "测试此处是否有问题");
            // 初始化 NotificationParser
            NotificationParser parser = new NotificationParser(config);
            //构建对象
            RequestParam requestParam=new RequestParam.Builder()
                    .serialNumber(serialNo)
                    .nonce(nonce)
                    .signature(signature)
                    .timestamp(timestamp)
                    // 若未设置signType，默认值为 WECHATPAY2-SHA256-RSA2048
                    .signType(signType)
                    .body(s1)
                    .build();
            System.out.println("我是parser：" + parser + "我是requestParam：" + requestParam);
            //创建转换对象
            ObjectMapper objectMapper = new ObjectMapper();
            //得到转换对象
            WechatPayNotification notification = objectMapper.readValue(requestParam.getBody(), WechatPayNotification.class);
            //得到byte
            byte[] apiV3Key  = wxPayConfig.getApiV3Key().getBytes(StandardCharsets.UTF_8);
            //得到byte
            byte[] associatedData = notification.getResource().getAssociatedData().getBytes(StandardCharsets.UTF_8);
            // 示例随机数（nonce）
            byte[] nonce2 = notification.getResource().getNonce().getBytes(StandardCharsets.UTF_8); // 替换为你的随机数，通常是 12 字节
            //密文
            String ciphertext = notification.getResource().getCiphertext();
            //创建实例
            AesUtil aesUtil = new AesUtil(apiV3Key);
            //调用解密方法
            String decryptedText = aesUtil.decryptToString(associatedData, nonce2, ciphertext);
            //结果
            System.out.println(decryptedText + "我是结果对象查看=======================");
            //得到结果
            WechatPayNotifyBody wechatPayNotifyBody = objectMapper.readValue(decryptedText, WechatPayNotifyBody.class);
            System.out.println(wechatPayNotifyBody + "我是结果对象查看=======================");
            //判断支付
            if (Objects.nonNull(wechatPayNotifyBody.getTradeStateDesc()) && wechatPayNotifyBody.getTradeStateDesc().equals("支付成功")){
                System.out.println("进入了此处");
                //执行修改数据库
                orderInfoMapper.update(null,new UpdateWrapper<OrderInfo>().lambda()
                        //订单号
                        .eq(OrderInfo::getOrderNo,wechatPayNotifyBody.getOutTradeNo())
                        //逻辑删除
                        .eq(OrderInfo::getDeleteFlag,Boolean.FALSE)
                        //设置状态
                        .set(OrderInfo::getOrderType, OrderInfoEnum.FukuanChengGong.getType())
                );
                //查询order进行给用户背包增加余额
                OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                        //订单号
                        .eq(OrderInfo::getOrderNo, wechatPayNotifyBody.getOutTradeNo())
                        //逻辑删除
                        .eq(OrderInfo::getDeleteFlag, Boolean.FALSE)
                        //状态
                        .eq(OrderInfo::getOrderType, OrderInfoEnum.FukuanChengGong.getType())
                );
                //判断订单不为 null
                if (Objects.nonNull(orderInfo) && Objects.nonNull(orderInfo.getUserId())){
                    //查询用户
                    SysUser sysUser = sysUserMapper.selectUserById(orderInfo.getUserId());
                    //判断查询的用户不为 null
                    if (Objects.nonNull(sysUser)){
                        //设置用户余额
                        BigDecimal sum = orderInfo.getFund().add(sysUser.getScore());
                        //设置用户余额
                        sysUser.setScore(sum);
                        //设置默认值
                        sysUser.setUpdateTime(new Date());
                        sysUser.setUpdateBy("平台充值");
                        //执行修改
                        sysUserMapper.updateUser(sysUser);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }



}
